import { useStore } from '@/hooks';
import { Button, Dialog, Icon, Form, ResponsiveGrid } from '@alifd/next';
import TauTable from '@/components/TauTable';
import UploadPanel from '@/components/UploadPanel';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid, feedbackModel, column } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { toJS, observable } from 'mobx';
import AttachmentForm from './AttachmentForm';

const FromItem = Form.Item;
const { Cell } = ResponsiveGrid;

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 16,
  },
  style: { marginBottom: 20 },
};

const DataForm = ({ onCancel, modal, ...formProps }) => {
  const { show, record, toClose } = modal || {};
  const { bobFeedbackStore: store } = useStore();
  const [feedback] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  useEffect(() => { if (toClose?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    const data = record;
    editCtx.origin = _.cloneDeep(data);
    _.assign(feedback, data);
  }, []);

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(feedback, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      isPreview
      {...formProps}
      value={feedback}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={feedback}
        columns={1}
        mode={'view'}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        fields={['userType', 'user.fullname', 'user.mobile', 'content', 'crDate']}
      />
      <AttachmentPanel feedback={feedback} mode={show} />
      <DrawerFooter>
        <FromItem>
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

/**
 * @description 附件组件
 */
const AttachmentPanel = observer(({ feedback, mode }) => {
  const [curAttachment, setCurAttachment] = useState();
  const [idx, setIdx] = useState(-1); // 当前选中的附件
  const isViewMode = mode === 'view';

  useEffect(() => {
    if (feedback.attachments?.length) setIdx(0);
  }, [feedback.attachments]);

  const handleDeleteAttachment = (i, e) => {
    feedback.attachments.splice(i, 1);
    if (i === idx) setIdx(i - 1);
    e.preventDefault();
    e.stopPropagation();
  };

  return (
    <>
      <TitleGrid title={<span>{t`附件`}</span>} />
      <ResponsiveGrid gap={[0, 30]} style={{ paddingLeft: 20 }}>
        <Cell colSpan={12}>
          <TauTable
            primaryKey="orderNumber"
            size="small"
            hidePagination
            tableLayout="fixed"
            dataSource={toJS(feedback?.attachments)}
            cellProps={(r) => ({ style: { cursor: 'pointer', backgroundColor: idx === r ? 'var(--color-fill1-1)' : 'unset' } })}
            columns={[
              { title: '#', dataIndex: 'idx', width: 44, cell: (_, i) => i + 1 },
              column('title', {}, feedbackModel.attachments[0]),
              column('description', {}, feedbackModel.attachments[0]),
              { title: t`附件个数`, dataIndex: 'cnt', width: 84, cell: (_, i, row) => <Button type="primary" text>{row.binaryId?.length}</Button> },
            ].concat(isViewMode ? [{ align: 'left', width: 30, cell: (_, i) => (i === idx && <Icon type="arrow-right" size="xs" style={{ color: 'var(--color-line1-4)' }} />) }] : [
              {
                title: <span style={{ paddingLeft: 16 }}>{t`操作`}</span>,
                dataIndex: 'title',
                align: 'left',
                width: 110,
                cell: (_, i, row) => (
                  <span>
                    <Button type="primary" text onClick={() => setCurAttachment(row)} >{t`编辑`}</Button>
                    <span>  </span>
                    <Button type="primary" text onClick={(e) => handleDeleteAttachment(i, e)} >{t`删除`}</Button>
                    {i === idx && <Icon type="arrow-right" size="xs" style={{ marginLeft: 16, color: 'var(--color-line1-4)' }} />}
                  </span>
                ),
              },
            ])}
            onRowClick={(_, index) => setIdx(index)}
          />
        </Cell>
        <Cell colSpan={5} style={{ paddingTop: 30 }}>
          {idx >= 0 && <UploadPanel
            isPreview={isViewMode}
            prefix={`chanel:${feedback.id}:attachment`}
            binaryIds={idx === -1 ? [] : toJS(feedback.attachments[idx]?.binaryId)}
            onUploaded={(meta) => {
              feedback.attachments[idx]?.binaryId.push(meta.binaryId);
            }}
            onRemove={(info) => {
              feedback.attachments[idx]?.binaryId.splice(feedback.attachments[idx]?.binaryId.findIndex((r) => r == info.uid), 1);
            }}
          />}
        </Cell>
      </ResponsiveGrid>
      <Dialog
        visible={!!curAttachment}
        onCancel={() => setCurAttachment(false)}
        onClose={() => setCurAttachment(false)}
        title={t`附件`}
        style={{ width: '50%' }}
        footer={null}
      >
        <AttachmentForm
          data={curAttachment}
          onSubmit={(data) => {
            _.assign(feedback.attachments[idx], data);
            setCurAttachment(false);
          }}
          onCancel={() => setCurAttachment(false)}
        />
      </Dialog>
    </>
  );
});

export default observer(DataForm);
